<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

/**
 * Class AdminLog
 * @package App\Models
 * @author  zjw
 */
class AdminLog extends Model{
    /**
     * @param $message
     * @param Admin|null $admin
     */
    public static function log($message , Admin $admin = null){
        if(is_null($admin)) {
            $admin = Auth::user();
        }
        $log = new self();
        $log->admin_id = $admin->id;
        $log->admin_username = $admin->username;
        $log->action = $message;
        $log->user_agent = request()->userAgent();
        $log->action_ip =  request()->ip();
        $log->save();
    }

    /**
     * @param $query
     * @param $username
     * @return mixed
     */
    public function scopeUsernameLike($query, $username)
    {
        return $query->when($username, function ($query) use ($username) {
            $query->where('admin_username','like',$username.'%');
        });
    }

    /**
     * @param $query
     * @param $action
     * @return mixed
     */
    public function scopeActionLike($query, $action)
    {
        return $query->when($action, function ($query) use ($action) {
            $query->where('action', 'like', '%' . $action . "%");
        });
    }
}